package com.common.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ArrayUtil;

public class BeanCopyUtil {

	private static Mapper mapper = DozerBeanMapperBuilder.buildDefault();
	
	/**
     * 简单的复制出新类型对象.
     */
    public static <S, D> D map(S source, Class<D> destinationClass) {
        return mapper.map(source, destinationClass);
    }

    /**
     * 简单的复制出新对象ArrayList
     */
    public static <S, D> List<D> mapList(Iterable<S> sourceList, Class<D> destinationClass) {
        List<D> destionationList = new ArrayList<>();
        for (S source : sourceList) {
            if (source != null) {
                destionationList.add(mapper.map(source, destinationClass));
            }
        }
        return destionationList;
    }

    /**
     * 简单复制出新对象数组
     */
    public static <S, D> D[] mapArray(final S[] sourceArray, final Class<D> destinationClass) {
        D[] destinationArray = ArrayUtil.newArray(destinationClass, sourceArray.length);
        int i = 0;
        for (S source : sourceArray) {
            if (source != null) {
                destinationArray[i] = mapper.map(sourceArray[i], destinationClass);
                i++;
            }
        }

        return destinationArray;
    }
    
	/**
	 * 复制属性到目标对象
	 * @param source
	 * @param target
	 * @param ingnoreSourceNull 是否忽略源对象空值
	 * @param ignoreProperties 源对象忽略属性
	 */
	public static void copy(Object source,Object target,boolean ingnoreSourceNull,String... ignoreProperties) {
		BeanUtil.copyProperties(source, target, 
				CopyOptions.create().setIgnoreNullValue(ingnoreSourceNull).setIgnoreProperties(ignoreProperties));
	}
	
	/**
	 * 目标对象添加属性值,只有目标属性为空才会添加
	 * @param source
	 * @param target
	 * @param ignoreProperties 源对象忽略属性
	 */
	public static void addTargeProperties(Object source,Object target,String... ignoreProperties) {
		Map<String,Object> targetMap=BeanUtil.beanToMap(target, false, true);
		Map<String,Object> sourceMap=BeanUtil.beanToMap(source, new LinkedHashMap<>(), 
				CopyOptions.create().setIgnoreProperties(ignoreProperties));
		sourceMap.putAll(targetMap);
		BeanUtil.copyProperties(sourceMap, target);
	}
}
